#!/usr/bin/php
<?php
	require_once(dirname(dirname(dirname(__FILE__)))."/lib/starter.php");

	$DB = Mysql::getInstance();

	$microtime_start = microtime(1);

	$create_clause = "";
	foreach ($G["ad_drills"] as $param_name => $param_descr) {

		$query = "DROP TABLE IF EXISTS `".$param_descr["table_name"]."`";
		if ($DB->query($query)->isError()) {
			exit;
		}

		$query = "CREATE TABLE `".$param_descr["table_name"]."` (
			`id` int unsigned NOT NULL AUTO_INCREMENT,
			`value` text NOT NULL,
			`amount` int unsigned NOT NULL DEFAULT '0',
			PRIMARY KEY (`id`)
		) ENGINE=MyISAM";
		if ($DB->query($query)->isError()) {
			exit;
		}

		if ($create_clause !== "") {
			$create_clause .= ", ";
		}
		$create_clause .= "`".$param_descr["param_field_name"]."` int unsigned NOT NULL DEFAULT 0";
	}

	$query = "DROP TABLE IF EXISTS `ads`";
	if ($DB->query($query)->isError()) {
		exit;
	}


	$query = "CREATE TABLE `ads` (
		`id` int unsigned NOT NULL AUTO_INCREMENT,
		`c_date` int unsigned NOT NULL DEFAULT 0,
		".$create_clause.",
		PRIMARY KEY (`id`)
	) ENGINE=MyISAM";
	if ($DB->query($query)->isError()) {
		exit;
	}


	$query = "DROP TABLE IF EXISTS `d`";
	if ($DB->query($query)->isError()) {
		exit;
	}

	$query = "CREATE TABLE `d` (
		`id` int unsigned AUTO_INCREMENT,
		`text` TEXT NOT NULL DEFAULT '',
		PRIMARY KEY (`id`)
	) ENGINE=MyISAM";
	if ($DB->query($query)->isError()) {
		exit;
	}

	foreach ($G["ad_drills"] as $param_name => $param_descr) {

		echo "Indexes for param: ".$param_name."...\n";

		$query = "ALTER TABLE `ads` ADD INDEX `".$param_descr["param_field_name"]."` (`".$param_descr["param_field_name"]."`)";
		if ($DB->query($query)->isError()) {
			exit;
		}

		$query = "ALTER TABLE `".$param_descr["table_name"]."` ADD INDEX `value` (`value`(255)), ADD INDEX `amount` (`amount`)";
		if ($DB->query($query)->isError()) {
			exit;
		}

		$query = "
			UPDATE
				`".$param_descr["table_name"]."`
			SET
				`".$param_descr["table_name"]."`.`amount` = (
					SELECT
						COUNT(*)
					FROM
						`ads`
					WHERE
						`ads`.`".$param_descr["param_field_name"]."` = `".$param_descr["table_name"]."`.`id`
				)";
		if ($DB->query($query)->isError()) {
			exit;
		}
	}

	$microtime_end = microtime(1);

	echo "Procced in: ".round($microtime_end - $microtime_start, 5)." seconds\n";
?>
